package Application.Utils;

import Application.Config.Config;
import Application.Exceptions.AppExceptions;
import Application.MainMenu;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.ArrayList;

public class StaticUtil
{
    protected StaticUtil() {}
    public static final String[] MainMetHod = new String[]{"null"};

    public static Config config = Config.configReader();
    public static void Init_config(){config = Config.configReader();}

    public static JFrame mainMenuFrame = new JFrame();
    public static JFrame summonerFrame = new JFrame();
    public static void clearSummonerFrame() { summonerFrame.setVisible(false);summonerFrame = null;}
    public static JFrame AI_Setter_Frame = null;
    public static JPanel AI_Panel = null;
    public static int ErrNum_Wrong_Parameter = 1;
    public static JTextArea errorReport = new JTextArea(10, 25);
    public static JScrollPane errorReportScrollPane;
    public static JPanel errorPanel = new JPanel();
    public static JFileChooser chooser = new JFileChooser();
    public static JMenuBar menuBar = null;

    public static void Init_AI_Panel ()
    {
        AI_Panel = null;
        AI_Panel = new JPanel();
        if (config.background_file != null)
        {
            JLabel Pic_Label = new JLabel(FrameUtil.getImage());
            AI_Panel.add(Pic_Label);
        }
    }
    public static void Init_AI_SetterFrame()
    {
        if (AI_Setter_Frame == null)
        {
            AI_Setter_Frame = new JFrame();
            AI_Setter_Frame.setTitle("AI设置器");
            AI_Setter_Frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            AI_Setter_Frame.setSize(1200, 500);
            JPanel panel = new JPanel();

            JButton set_AI_Pic = new JButton("设置AI图片");
            set_AI_Pic.setFont(config.fontGetter());
            set_AI_Pic.addActionListener(e -> {
                JFileChooser chooser = new JFileChooser();
                chooser.setFont(config.fontGetter());
                chooser.setDialogTitle("选择你喜欢的AI图片吧");
                chooser.setAcceptAllFileFilterUsed(false);
                chooser.addChoosableFileFilter(new FileFilter() {
                    @Override
                    public boolean accept(File f) {
                        if (f.isDirectory()) {
                            return true;
                        } else return f.getName().endsWith(".png") || f.getName().endsWith(".jpg");
                    }

                    @Override
                    public String getDescription() {
                        return "图片文件文件(.png/.jpg)";
                    }
                });
                chooser.setFileSelectionMode(JFileChooser.OPEN_DIALOG);
                int result = chooser.showOpenDialog(mainMenuFrame);
                if (result == JFileChooser.APPROVE_OPTION)
                {
                    config.background_file = chooser.getSelectedFile();
                    Config.configWriter(config);
                }
            });

            panel.add(set_AI_Pic);

            AI_Setter_Frame.add(panel);
            AI_Setter_Frame.addWindowListener(new WindowListener() {
                @Override
                public void windowOpened(WindowEvent e) {

                }

                @Override
                public void windowClosing(WindowEvent e) {
                    AI_Setter_Frame = null;
                }

                @Override
                public void windowClosed(WindowEvent e) {

                }

                @Override
                public void windowIconified(WindowEvent e) {

                }

                @Override
                public void windowDeiconified(WindowEvent e) {

                }

                @Override
                public void windowActivated(WindowEvent e) {

                }

                @Override
                public void windowDeactivated(WindowEvent e) {

                }
            });
            AI_Setter_Frame.setVisible(true);
        }
    }
    public static void Init_menuBar()
    {
        menuBar = null;
        menuBar = new JMenuBar();
        JMenu mainMenu = new JMenu("选项");
        JMenu mn_fontSetter = new JMenu("字体");
        JMenuItem mi_fontSetter_MS_Song = new JMenuItem("宋体");
        JMenuItem mi_fontSetter_Imitation_Song_Dynasty = new JMenuItem("仿宋");
        JMenuItem mi_backMainMenu = new JMenuItem("返回主菜单");
        JMenuItem mi_close = new JMenuItem("关闭");

        mi_fontSetter_MS_Song.setFont(Config.font_1);
        mi_fontSetter_MS_Song.addActionListener(e -> StaticUtil.fontChanger(0));
        mn_fontSetter.add(mi_fontSetter_MS_Song);
        mi_fontSetter_Imitation_Song_Dynasty.addActionListener(e -> StaticUtil.fontChanger(1));
        mi_fontSetter_Imitation_Song_Dynasty.setFont(Config.font_2);
        mi_backMainMenu.setFont(config.fontGetter());
        mi_backMainMenu.addActionListener(e -> {
            StaticUtil.clearSummonerFrame();
            StaticUtil.mainMenuFrame = null;
            MainMenu.main(StaticUtil.MainMetHod);
        });
        mn_fontSetter.add(mi_fontSetter_Imitation_Song_Dynasty);
        mn_fontSetter.setFont(config.fontGetter());
        mainMenu.add(mn_fontSetter);
        mainMenu.add(mi_backMainMenu);
        mainMenu.add(mi_close);
        mainMenu.setFont(config.fontGetter());
        mi_close.setFont(config.fontGetter());
        mi_close.addActionListener(e -> System.exit(0));

        JMenu windows = new JMenu("界面");
        JMenuItem errorReportChange = new JMenuItem("开/关错误报告");

        windows.setFont(config.fontGetter());
        errorReportChange.setFont(config.fontGetter());
        errorReportChange.addActionListener(event ->
        {
            errorPanel.setVisible(!errorPanel.isVisible());
            SwingUtilities.updateComponentTreeUI(summonerFrame);
        });
        windows.add(errorReportChange);

        menuBar.add(mainMenu);
        menuBar.add(windows);
    }
    public static void Init_menuBar(JFrame frame)
    {
            Init_menuBar();
            frame.setJMenuBar(menuBar);
    }
    public static void Init_errorReportPane()
    {
        errorPanel.removeAll();
        errorReport = new JTextArea(10, 25);

        StaticUtil.errorReport.setLineWrap(true);
        StaticUtil.errorReport.setEditable(false);
        StaticUtil.errorReport.setFont(config.fontGetter());
        StaticUtil.errorReport.setBackground(Color.BLACK);
        StaticUtil.errorReport.setForeground(Color.RED);
        StaticUtil.errorReport.setSelectionColor(Color.BLUE);
        errorReportScrollPane = new JScrollPane(StaticUtil.errorReport);
        errorReportScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        errorReportScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        BoxLayout Box_x = new BoxLayout(errorPanel, BoxLayout.X_AXIS);
        errorPanel.setLayout(Box_x);
        errorPanel.setBackground(Color.BLACK);
        errorPanel.add(errorReportScrollPane, BorderLayout.WEST);
    }

    public static void fontChanger(int i){
        try {
            config.fontNumSetter(i);
            SwingUtilities.updateComponentTreeUI(summonerFrame);
            Config.configWriter(config);
        } catch (AppExceptions ex) {
            String err = ex.ErrGetter();
            StaticUtil.errorReport.append(err + "\n");
        }
    }
    public static String StringListGetter(String index, Object[] items)
    {
        StringBuilder output = new StringBuilder();
        for(Object t : items){
            output.append("      <").append(index).append(">").append(t).append("</").append(index).append(">\n");
        }
        return output.toString();
    }
    public static String StringListGetter(Object[] index, Object[] items)
    {
        StringBuilder output = new StringBuilder();
        for(int i = 0 ; i < index.length; i++){
            try {
                output.append("      <").append(index[i]).append(">").append(items[i]).append("</").append(index[i]).append(">\n");
            } catch (ArrayIndexOutOfBoundsException e) {
                e.printStackTrace();
                StaticUtil.errorReport.append(e.getMessage() + "\n" + "AI:为什么会这样子呢，唔，不应该啊\n");
            }
        }
        return output.toString();
    }

    public static Object getRandomFromArray(Object[] array){return array[((int) Math.round( Math.random()*array.length-1))];}
    public static Object getRandomFromArray(ArrayList arrayList){return arrayList.get((int) Math.round( Math.random()*arrayList.size()-1));}

    public static String StringChecker(String str,String baseValue,String errorMessage){
        String value = baseValue;
        if (str == null)
        {
            return errorMessage;
        }
        if (!str.equals(""))
        {
            value = str;
        }else
        {
            StaticUtil.errorReport.append(errorMessage+"\n");
        }
        return value;
    }
    public static int IntegerChecker(String value,int baseValue,String widgetName){
        try {
            return Integer.parseInt(value);
        }catch (Exception ex) {
            StaticUtil.errorReport.append(ex.getMessage()+"\n");
            StaticUtil.errorReport.append("不合法的输入，位置："+widgetName+"\n");
            ex.printStackTrace();
        }
        return baseValue;
    }
    public static double DoubleChecker(String value,double baseValue,String widgetName){
        try {
            return Double.parseDouble(value);
        }catch (Exception ex) {
            StaticUtil.errorReport.append(ex.getMessage()+"\n");
            StaticUtil.errorReport.append("不合法的输入，位置："+widgetName+"\n");
            ex.printStackTrace();
        }
        return baseValue;
    }
}
